using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using TinyJson;
using UnityEngine;
using UnityEngine.Events;
using Voodoo.Sauce.Common.Utils;
using Voodoo.Sauce.Core;
using Voodoo.Sauce.Internal;

namespace Voodoo.Sauce.Privacy.UI
{
	public class PrivacyUIManager : IPrivacyUIManager
	{
		private const string TAG = "PRIVACY_UI_MANAGER";

		private Dictionary<string, object> _privacyTextDictionary;

		private PrivacyTexts _privacyTexts;

		private Dictionary<string, string> _constTexts;

		private IPrivacyCanvas _privacyCanvas;

		private VoodooSettings _voodooSettings;

		private PrivacyConsent _privacyConsent;

		private bool _isLearnMoreScreenInitialized;

		private bool _isParternScreenInitialized;

		private bool _isDeleteScreenInitialized;

		private bool _isAccessScreenInitialized;

		private PrivacyScreen.Parameters _privacyScreenParameters;

		public void Initialize(IPrivacyUIManagerParameters parameters)
		{
			_privacyCanvas = parameters.privacyCanvas;
			_voodooSettings = parameters.voodooSettings;
			Dictionary<string, string> replaceTexts = new Dictionary<string, string>
			{
				{
					"@COLOR",
					"#" + ColorUtility.ToHtmlStringRGB(_voodooSettings.GdprPrimaryColor)
				},
				{
					"@GAME_NAME",
					Application.productName
				},
				{
					"@ANALYTICS_SDK_LIST",
					Environment.NewLine + string.Join(", ", PrivacyUtils.GetAnalyticsNames())
				},
				{
					"@ADS_SDK_LIST",
					Environment.NewLine + string.Join(", ", PrivacyUtils.GetAdNetworkNames())
				},
				{ "@STUDIO_NAME", "Voodoo" },
				{
					"<br>",
					Environment.NewLine
				}
			};
			if (parameters.gdprTexts != null)
			{
				_privacyTexts = parameters.gdprTexts.FromJson<PrivacyTexts>(replaceTexts);
				if (_privacyTexts == null)
				{
					VoodooLog.LogError(Module.PRIVACY, "PRIVACY_UI_MANAGER", "Couldn't parse string '" + parameters.gdprTexts + "' to JSON");
					throw new Exception("Couldn't parse text to json.");
				}
			}
		}

		public async Task<PrivacyConsent> GetPrivacyConsent()
		{
			_privacyConsent = null;
			_privacyScreenParameters = new PrivacyScreen.Parameters
			{
				mainColor = _voodooSettings.GdprPrimaryColor,
				title = _privacyTexts?.title,
				intro = _privacyTexts?.intro_thanks,
				outro = _privacyTexts?.outro_thanks,
				advertisingText = _privacyTexts?.consent_advertising,
				advertisingAction = OpenParternScreen,
				advertisingDefaultValue = false,
				advertisingActive = true,
				analyticsText = _privacyTexts?.consent_analytics,
				analyticsAction = OpenParternScreen,
				analyticsDefaultValue = false,
				analyticsActive = true,
				ageText = _privacyTexts?.pgpd_sixteen,
				ageAction = OpenPolicyPage,
				ageDefaultValue = false,
				accept = _privacyTexts?.play,
				acceptCallback = delegate(PrivacyConsent consent)
				{
					UpdateConsent(consent);
				},
				learnMore = _privacyTexts?.more,
				learnMoreAction = OpenLearnMoreScreen,
				automaticallyAccept = false,
				isSeparatorsActive = true
			};
			_privacyCanvas.OpenPrivacyScreen(_privacyScreenParameters);
			while (_privacyConsent == null)
			{
				await Task.Yield();
			}
			return _privacyConsent;
		}

		private void OpenLearnMoreScreen()
		{
			_privacyCanvas.ClosePrivacyScreen();
			if (!_isLearnMoreScreenInitialized)
			{
				LearnMoreScreen.Parameters parameters = new LearnMoreScreen.Parameters
				{
					mainColor = _voodooSettings.GdprPrimaryColor,
					header = _privacyTexts?.title2,
					intro = _privacyTexts?.intro2,
					game = _privacyTexts?.game,
					ads = _privacyTexts?.ads,
					bug = _privacyTexts?.bug,
					outro = _privacyTexts?.outro2,
					backCallback = delegate
					{
						_privacyCanvas.CloseLearnMoreScreen();
						_privacyCanvas.OpenPrivacyScreen();
					},
					back = _privacyTexts?.back
				};
				_privacyCanvas.OpenLearnMoreScreen(parameters);
				_isLearnMoreScreenInitialized = true;
			}
			else
			{
				_privacyCanvas.OpenLearnMoreScreen();
			}
		}

		private void OpenParternScreen()
		{
			_privacyCanvas.ClosePrivacyScreen();
			if (!_isParternScreenInitialized)
			{
				ParternsScreen.Parameters p = new ParternsScreen.Parameters
				{
					mainColor = _voodooSettings.GdprPrimaryColor,
					header = _privacyTexts?.partners,
					intro = _privacyTexts?.intro_partners,
					advertising = _privacyTexts?.advertising,
					advertisingUrls = PrivacyUtils.GetAdvertisingPrivacyPolicyUrls(),
					analytics = _privacyTexts?.analytics,
					analyticsUrls = PrivacyUtils.GetAnalyticsPrivacyPolicyUrls(),
					backCallback = delegate
					{
						_privacyCanvas.CloseParternsScreen();
						_privacyCanvas.OpenPrivacyScreen();
					},
					back = _privacyTexts?.back
				};
				_privacyCanvas.OpenPartnersScreen(p);
				_isParternScreenInitialized = true;
			}
			else
			{
				_privacyCanvas.OpenPartnersScreen();
			}
		}

		private void OpenPolicyPage()
		{
			Application.OpenURL(_privacyTexts?.privacy_policy_url);
		}

		public void OpenSettingsScreen(bool adsConsent, bool analyticsConsent, bool idfaAuthorizationStatusDeniedOrRestricted, string idfa, UnityAction<PrivacyUpdate> updatePrivacy, UnityAction<string> deleteData, UnityAction<UserDetails> accessData, UnityAction tryOpenDebugger, UnityAction closeSettingsScreen)
		{
			SettingsScreen.Parameters p = new SettingsScreen.Parameters
			{
				mainColor = _voodooSettings.GdprPrimaryColor,
				title = _privacyTexts?.data_sharing,
				intro = ((PlatformUtils.UNITY_IOS && idfaAuthorizationStatusDeniedOrRestricted) ? (_privacyTexts?.data_sharing_subtitle + "\n\n") : "") + _privacyTexts?.intro3,
				advertisingValue = adsConsent,
				advertising = _privacyTexts?.advertising,
				advertisingUrls = PrivacyUtils.GetAdvertisingPrivacyPolicyUrls(),
				analyticsValue = analyticsConsent,
				analytics = _privacyTexts?.analytics,
				analyticsUrls = PrivacyUtils.GetAnalyticsPrivacyPolicyUrls(),
				accessDataAction = delegate
				{
					OpenAccessDataScreen(idfa, accessData, tryOpenDebugger, delegate
					{
						_privacyCanvas.OpenSettingsScreen();
					});
					CloseSettingsScreen();
				},
				accessDataText = _privacyTexts?.access_data,
				deleteDataCallback = delegate
				{
					OpenDeleteScreen(idfa, deleteData, delegate
					{
						_privacyCanvas.OpenSettingsScreen();
					});
					CloseSettingsScreen();
				},
				deleteDataText = _privacyTexts?.delete_data,
				saveAction = updatePrivacy,
				saveText = _privacyTexts?.confirm,
				closeCallback = closeSettingsScreen,
				closeText = _privacyTexts?.close
			};
			_privacyCanvas.OpenSettingsScreen(p);
		}

		public void CloseSettingsScreen()
		{
			_privacyCanvas.CloseSettingsScreen();
		}

		public void OpenCmpSettingsScreen(bool idfaAuthorizationStatusDeniedOrRestricted, string idfa, UnityAction openCmpSettings, UnityAction<string> deleteData, UnityAction<UserDetails> accessData, UnityAction tryOpenDebugger, UnityAction closeCmpSettingsScreen)
		{
			CmpSettingsScreen.Parameters p = new CmpSettingsScreen.Parameters
			{
				mainColor = _voodooSettings.GdprPrimaryColor,
				title = _privacyTexts?.data_sharing,
				intro = ((!(PlatformUtils.UNITY_IOS && idfaAuthorizationStatusDeniedOrRestricted)) ? "" : _privacyTexts?.data_sharing_subtitle),
				accessDataAction = delegate
				{
					OpenAccessDataScreen(idfa, accessData, tryOpenDebugger, delegate
					{
						_privacyCanvas.OpenCmpSettingsScreen();
					});
					CloseCmpSettingsScreen();
				},
				accessDataText = _privacyTexts?.access_data,
				deleteDataCallback = delegate
				{
					OpenDeleteScreen(idfa, deleteData, delegate
					{
						_privacyCanvas.OpenCmpSettingsScreen();
					});
					CloseCmpSettingsScreen();
				},
				deleteDataText = _privacyTexts?.delete_data,
				openCmpSettingsAction = openCmpSettings,
				openCmpSettingsText = GetOpenCmpSettingsText(),
				closeCallback = closeCmpSettingsScreen,
				closeText = _privacyTexts?.close
			};
			_privacyCanvas.OpenCmpSettingsScreen(p);
		}

		private static string GetOpenCmpSettingsText()
		{
			return PrivacyUtils.GetLocale() switch
			{
				"DE" => "meine Zustimmung ändern", 
				"ES" => "modificar mi consentimiento", 
				"FR" => "Modifier mon consentement", 
				"NL" => "mijn toestemming wijzigen", 
				"PL" => "zmodyfikować moją zgodę", 
				"SW" => "ändra mitt samtycke", 
				"IT" => "modificare il mio consenso", 
				_ => "Modify my consent", 
			};
		}

		public void CloseCmpSettingsScreen()
		{
			_privacyCanvas.CloseCmpSettingsScreen();
		}

		private void OpenDeleteScreen(string idfa, UnityAction<string> deletePrivacy, UnityAction closeAction)
		{
			if (!_isDeleteScreenInitialized)
			{
				DeleteScreen.Parameters p = new DeleteScreen.Parameters
				{
					mainColor = _voodooSettings.GdprPrimaryColor,
					title = _privacyTexts?.delete_data,
					intro = _privacyTexts?.intro_delete,
					emailTitle = _privacyTexts?.email,
					idfaTitle = _privacyTexts?.idfa,
					idfa = idfa,
					deleteText = _privacyTexts?.delete_data,
					deleteCallback = deletePrivacy,
					closeText = _privacyTexts?.close,
					closeCallback = delegate
					{
						_privacyCanvas.CloseDeleteScreen();
						closeAction?.Invoke();
					}
				};
				_privacyCanvas.OpenDeleteScreen(p);
				_isDeleteScreenInitialized = true;
			}
			else
			{
				_privacyCanvas.OpenDeleteScreen();
			}
		}

		public void CloseDeleteScreen()
		{
			_privacyCanvas.CloseDeleteScreen();
		}

		private void OpenAccessDataScreen(string idfa, UnityAction<UserDetails> sendRequestAction, UnityAction tryOpenDebugger, UnityAction closeAction)
		{
			if (!_isAccessScreenInitialized)
			{
				AccessDataScreen.Parameters p = new AccessDataScreen.Parameters
				{
					mainColor = _voodooSettings.GdprPrimaryColor,
					title = _privacyTexts?.access_data,
					intro = _privacyTexts?.intro4,
					idfaTitle = _privacyTexts?.idfa,
					idfa = idfa,
					emailTitle = _privacyTexts?.email,
					sendRequestAction = sendRequestAction,
					sendRequestButtonText = _privacyTexts?.send,
					closeAction = delegate
					{
						_privacyCanvas.CloseAccessDataScreen();
						closeAction?.Invoke();
					},
					closeButtonText = _privacyTexts?.close,
					tryOpenDebugger = delegate
					{
						CloseAccessDataScreen();
						tryOpenDebugger?.Invoke();
					}
				};
				_privacyCanvas.OpenAccessDataScreen(p);
				_isAccessScreenInitialized = true;
			}
			else
			{
				_privacyCanvas.OpenAccessDataScreen();
			}
		}

		public void CloseAccessDataScreen()
		{
			_privacyCanvas.CloseAccessDataScreen();
		}

		private void OpenPopupScreen(string title, string message, string closeButtonText, UnityAction closeCallback)
		{
			PopupScreen.Parameters p = new PopupScreen.Parameters
			{
				mainColor = _voodooSettings.GdprPrimaryColor,
				title = title,
				message = message,
				closeCallback = closeCallback,
				closeButtonText = closeButtonText
			};
			_privacyCanvas.OpenPopupScreen(p);
		}

		public void ClosePopupScreen()
		{
			_privacyCanvas.ClosePopupScreen();
		}

		public void OpenPrivacyNotInitializedPopupScreen(UnityAction closeCallback, VoodooSettings voodooSettings, IPrivacyCanvas privacyCanvas)
		{
			_voodooSettings = voodooSettings;
			_privacyCanvas = privacyCanvas;
			string title = "Error";
			string message = "Sorry, you must have an internet connection to access and change your privacy settings.";
			string closeButtonText = "Close";
			OpenPopupScreen(title, message, closeButtonText, closeCallback);
		}

		public void OpenUpdatePrivacySuccessPopupScreen(UnityAction closeCallback)
		{
			string title = _privacyTexts?.success_title;
			string message = "Your request has been registered, please restart the app to apply the changes.";
			string closeButtonText = _privacyTexts?.close;
			OpenPopupScreen(title, message, closeButtonText, closeCallback);
		}

		public void OpenUpdatePrivacyErrorPopupScreen(UnityAction closeCallback)
		{
			string title = _privacyTexts?.error_title;
			string message = _privacyTexts?.error;
			string closeButtonText = _privacyTexts?.close;
			OpenPopupScreen(title, message, closeButtonText, closeCallback);
		}

		public void OpenSuccessPopupScreen(UnityAction closeCallback)
		{
			string title = _privacyTexts?.success_title;
			string message = _privacyTexts?.success;
			string closeButtonText = _privacyTexts?.close;
			OpenPopupScreen(title, message, closeButtonText, closeCallback);
		}

		public void OpenErrorPopupScreen(string errorMessage, UnityAction closeCallback)
		{
			string title = _privacyTexts?.error_title;
			string closeButtonText = _privacyTexts?.close;
			OpenPopupScreen(title, errorMessage, closeButtonText, closeCallback);
		}

		public void OpenConnexionErrorPopupScreen(UnityAction closeCallback)
		{
			string title = _privacyTexts?.error_title;
			string message = _privacyTexts?.error;
			string closeButtonText = _privacyTexts?.close;
			OpenPopupScreen(title, message, closeButtonText, closeCallback);
		}

		public void OpenEmailErrorPopupScreen(UnityAction closeCallback)
		{
			string title = _privacyTexts?.error_title;
			string message = "Invalid email address.";
			string closeButtonText = _privacyTexts?.close;
			OpenPopupScreen(title, message, closeButtonText, closeCallback);
		}

		public void OpenLoadingScreen()
		{
			_privacyCanvas.OpenLoadingScreen();
		}

		public void CloseLoadingScreen()
		{
			_privacyCanvas.CloseLoadingScreen();
		}

		private void UpdateConsent(PrivacyConsent consent)
		{
			_privacyConsent = consent;
			_privacyCanvas.ClosePrivacyScreen();
		}
	}
}
